// pages/expense/list/index.ts
import Toast from "tdesign-miniprogram/toast"
import ExpenseApi from "../../../api/ExpenseApi"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
  },
  pageNum: 1,
  pageSize: 10,
  total: 0,
  getList() {
    let { userId } = wx.getStorageSync("user")
    ExpenseApi.page({ index: this.pageNum, size: this.pageSize, userId }).then((res: any) => {
      let list = res.data.map((i: Expense) => {
        i.expenseTime = i.expenseTime?.substring(0, 10)
        return i
      })
      this.setData({ list })
      this.total = res.total
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  addList() {
    let { userId } = wx.getStorageSync("user")
    ExpenseApi.page({ index: this.pageNum, size: this.pageSize, userId }).then((res: any) => {
      let list = res.data.map((i: Expense) => {
        i.expenseTime = i.expenseTime?.substring(0, 10)
        return i
      })
      this.setData({ list: this.data.list.concat(list) })
      this.total = res.total
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  handleFilter() {
    this.pageNum = 1
    this.getList()
  },
  handleClick() {
    wx.navigateTo({
      url: '/pages/expense/expense'
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.handleFilter()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.pageNum += 1
    this.addList()
  },
  onShow(): void | Promise<void> {
    this.handleFilter()
  }
})
